const speakDirective = {
    mounted(el, binding) {
        const speech = new SpeechSynthesisUtterance()
        speech.lang = 'zh-CN' // 设置中文朗读
        speech.rate = binding.value?.rate || 1 // 语速设置

        // 获取需要朗读的文本
        const getText = () => {
            return binding.arg ?
                el.querySelector(binding.arg).innerText :
                el.innerText
        }

        // 点击触发朗读
        el.addEventListener('click', () => {
            if (window.speechSynthesis.speaking) {
                window.speechSynthesis.cancel()
            }
            speech.text = getText()
            window.speechSynthesis.speak(speech)
        })

        // 添加朗读状态样式
        el.style.cursor = 'pointer'
        el.classList.add('speakable')
    },

    beforeUnmount(el) {
        window.speechSynthesis.cancel()
    }
}

export default speakDirective
